from django.http import JsonResponse
from django.views import View
from django.contrib import auth
from django.urls import reverse
### 使用login_required装饰器~~对需要用户认证的视图进行认证！！！！！！！！！！！~~~~~~~~~
#########  当然也可以在中间件中做一下 权限的过滤~~~
from django.contrib.auth.decorators import login_required
from django.shortcuts import render,redirect,HttpResponse

from manager.models import UserInfo as User
from my_forms.register_form import Register_form


class Login(View):

    def get(self,request):
       return render(request,"login.html")

    def post(self,request):
        status_dic = {"login_status": 0}
        dic = request.POST.dict()
        # print("1>>>>>",dic)
        # 把csrftoken认证与图片验证码的键值对对去掉
        dic.pop("csrfmiddlewaretoken")
        verification_code = dic.pop("verification_code")
        # 从session中获取随机验证码的数值！
        if verification_code.upper() == request.session["verification_code"].upper():
            # print("2>>>>>>",dic)
            ret = auth.authenticate(**dic)
            # print("ret>>>>>",ret)
            if ret:
                # 设置session
                auth.login(request, ret)
                status_dic["login_status"] = 1
                status_dic["url"] = reverse('talk_room')
                ret = JsonResponse(status_dic)
                ret.set_cookie("user", dic["username"])
                return ret
            else:
                status_dic["err_code"] = 10
        else:
            status_dic["err_code"] = 11
        return JsonResponse(status_dic)

class Register(View):

    def get(self,request):
        form = Register_form()
        return render(request,"register.html",locals())

    def post(self,request):
        dic = request.POST.dict()
        print(dic)
        form = Register_form(dic)
        if form.is_valid():
            data = form.cleaned_data
            data.pop("password2")
            User.objects.create_user(**data)
            ret = redirect('login')
            ret.set_cookie("user", data["username"])
            return ret
        return render(request, 'register.html', locals())

class Logout(View):

    def get(self,request):
        # 清除session
        auth.logout(request)
        return  redirect("login")

class Update_pwd(View):
    def get(self,request):
        return render(request,"update_pwd.html")

    def post(self,request):
        dic = request.POST.dict()
        status_dic = {"update_status": 0,"err_code":None}
        print(request.user) # wanghw199102
        # 新密码不能为空
        if not dic["new_password"]:
            status_dic["err_code"] = 0
            return JsonResponse(status_dic)
        # 旧密码输入正确可以修改密码
        if request.user.check_password(dic["old_password"]):
            if dic["new_password"] == dic["new_password2"]:
                request.user.set_password(dic["new_password"])
                request.user.save()
                status_dic["update_status"] = 1
                status_dic["url"] = reverse("login")
            else:
                status_dic["err_code"] = 21
        else:
            status_dic["err_code"] = 20
        return JsonResponse(status_dic)

class TalkRoom(View):

    def get(self,request):
        return render(request,"talk_room.html")


# talk_dic = {}
talk_content = []
user_info = {}
user_talk = {}

def accept_message(request):
    # print(request.POST)
    data = request.POST.dict()
    for key in data:
        dic = {"message":data[key],"user":key}
        talk_content.append(dic)
    return HttpResponse('ok')

def accept_single_message(request):
    # print(request.POST)
    I = request.POST.get("self")
    he = request.POST.get("who_talk_with")
    content = request.POST.get("content")

    user_talk[I].setdefault(he,[])
    user_talk[he].setdefault(I,[])
    if I != he:
        user_talk[I][he].append({"user":I,"message":content})
        user_talk[he][I].append({"user":I,"message":content})
    else:
        user_talk[I][he].append({"user": I, "message": content})
        user_talk[I][he].append({"user": "管理员", "message": "抱歉，您不可以给自己发信息"})

    print(user_talk)
    return HttpResponse("ok")

def send_user(request):
    # print(user_info)
    return JsonResponse(user_info)

def send_message(request):
    # print(request.GET)
    data = request.GET.dict()
    for key in data:
        user = key
        num = int(data[key])

    user_info.setdefault(user, {})
    user_talk.setdefault(user,{})

    # 要发送给客户端的数据列表
    temp = []
    talk_content_len = len(talk_content)
    if num:
        for cont in talk_content[num:talk_content_len]:
            if cont["user"] != user:
                temp.append(cont)
    else:
        temp = talk_content[num:talk_content_len]
    temp.append(talk_content_len)
    return JsonResponse(temp,safe=False)

def send_single_message(request):
    # print(request.GET)
    I = request.GET.get('self')
    he = request.GET.get('he')
    num = int(request.GET.get('single_message_num'))
    temp = []
    try:
        talk_content_list = user_talk[I][he]
    except:
        return JsonResponse(temp,safe=False)
    talk_list_len = len(talk_content_list)
    if num:
        for cont in talk_content_list[num:talk_list_len]:
            if cont["user"] != I:
                temp.append(cont)
    else:
        temp = talk_content_list[num:talk_list_len]
    # print("temp  !!",temp)
    temp.append(talk_list_len)

    return JsonResponse(temp, safe=False)

def send_single_message_len(request):
    temp = {}
    I = request.GET.get('self')
    # print("聊天的字典内容：",user_talk[I])
    for key in user_talk[I]:
        if key != I:
            temp[key] = len(user_talk[I][key])
    # print("发送单人消息长度 ",temp)
    return JsonResponse(temp)

def close_browser(request):
    # print(request.GET)
    del user_info[request.GET.get("user")]
    return HttpResponse("ok")
